using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Kaleida.ServiceMonitor.Framework;
using Kaleida.ServiceMonitor.Model.ColourSpecifications;

namespace Kaleida.ServiceMonitor.Model.Runtime
{
    internal class StateColourationStrategy : IStateColourationStrategy
    {
        private readonly List<IStateColourSpecification> completeSpecificationList;

        public StateColourationStrategy()
            : this(BuildDefault())
        {
        }

        public StateColourationStrategy(IEnumerable<IStateColourSpecification> specifications)
        {
        	completeSpecificationList = new[] {new NotMonitoringColourSpecification()}
        		.Concat(specifications)
        		.Concat(new[] {new FixedColourSpecification(Color.White)}).ToList();
        }

        public static StateColourationStrategy Parse(string specificationString)
        {
        	var components = specificationString.Split(';', ',').Where(i=>i.Trim() != "");

        	var predicates = components.Select(RangeStateColourSpecification.Parse).ToList();

            return new StateColourationStrategy(predicates);
        }

    	private static IEnumerable<IStateColourSpecification> BuildDefault()
        {
            return new IStateColourSpecification[]
                       {
                           RangeStateColourSpecification.WithBounds(Color.LightGreen, FailureCountMetric.Instance, 0, 0),
                           RangeStateColourSpecification.WithBounds(Color.Yellow, FailureCountMetric.Instance, 1, 1),
                           RangeStateColourSpecification.WithBounds(Color.Orange, FailureCountMetric.Instance, 2, 9),
                           RangeStateColourSpecification.WithBounds(Color.LightCoral, FailureCountMetric.Instance, 10, 99),
                           RangeStateColourSpecification.WithLowerBound(Color.Crimson, FailureCountMetric.Instance, 100)
                       };
        }

        public Color GetNotificationColour(IMonitorState state)
        {
			return completeSpecificationList.First(i => i.IsMatch(state)).Colour;
        }

        public string Description
        {
            get { return completeSpecificationList.Select(i=>i.Description).JoinWith(", "); }
        }
    }
}